import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/',
    component: () => import('../views/Manage.vue'),
    redirect: "/home",
    children: [
      { path: '/home', name: '首页', component: () => import('../views/Home.vue')},
      { path: '/own', name: '个人信息', component: () => import('../views/Own.vue')},
      { path: '/password', name: '修改密码', component: () => import('../views/Password.vue')},
      {
        path: '/commodities',
        name: '饮料管理',
        component: () => import('../views/Commodities.vue')
      },
      {
        path: '/toppings',
        name: '小料管理',
        component: () => import('../views/Toppings.vue')
      },
      {
        path: '/orders',
        name: '订单管理',
        component: () => import('../views/Orders.vue')
      },
      {
        path: '/refund',
        name: '退款申请',
        component: () => import('../views/Refund.vue')
      },
      {
        path: '/holder',
        name: '置物格管理',
        component: () => import('../views/Holder.vue')
      },
      {
        path: '/customer',
        name: '顾客管理',
        component: () => import('../views/Customer.vue')
      },
      {
        path: '/cancelOrder',
        name: '撤单申请',
        component: () => import('../views/CancelOrder.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 提供一个重置路由的方法
export const resetRouter = () => {
  router.matcher = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
  })
}

// 路由守卫
router.beforeEach((to, from, next) => {
  localStorage.setItem("currentPathName", to.name)  // 设置当前的路由名称
  store.commit("setPath")

  // 检查 localStorage 中的 individual 值
  const individual = localStorage.getItem("individual") ? JSON.parse(localStorage.getItem("individual")) : {};

  // 如果 individual 是空对象，跳转到 login 页面
  if (Object.keys(individual).length === 0 && to.path !== '/login') {
    next('/login'); // 重定向到登录页
    return; // 防止继续执行其他路由逻辑
  }

  // 如果是匹配不到的路由
  if (!to.matched.length) {
    const storeMenus = localStorage.getItem("menus");
    if (storeMenus) {
      next("/404");
    } else {
      // 跳回登录页面
      next("/login");
    }
  }

  // 其他的情况都放行
  next();
});

export default router